package com.jrx.anytxn.param.transaction.job.billCompare.config;

import com.google.common.collect.Maps;
import com.jrx.anytxn.param.transaction.config.AnytxnBatchConfigProperties;
import com.jrx.anytxn.param.transaction.config.BillCompareConfig;
import com.jrx.anytxn.param.transaction.job.billCompare.bean.ThirdBillDetilReadBean;
import com.jrx.anytxn.param.transaction.job.billCompare.step.BillDetailWriter;
import com.jrx.anytxn.param.transaction.job.billCompare.step.WexinDetailReadListener;
import com.jrx.anytxn.param.transaction.job.billCompare.step.WexinPaymentLogProcessor;
import com.jrx.anytxn.param.transaction.job.billCompare.step.WexinRefundLogProcessor;
import com.jrx.anytxn.transaction.entity.TlPaymentLog;
import com.jrx.anytxn.transaction.entity.TlRefundLog;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisPagingItemReader;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;


/**
 * 微信还款对账任务定义
 *
 * @author : zcc
 * 2020/11/30
 */
@Configuration
public class WexinBillCompareConfiguration {

    @Resource(name = "bizSqlSessionFactory")
    SqlSessionFactory bizSqlSessionFactory;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private AnytxnBatchConfigProperties anytxnBatchConfigProperties;

    @Autowired
    private BillDetailWriter billDetailWriter;

    @Autowired
    private WexinPaymentLogProcessor wexinPaymentLogProcessor;

    @Autowired
    private WexinRefundLogProcessor wexinRefundLogProcessor;

    @Autowired
    private WexinDetailReadListener wexinDetailReadListener;

    @Resource
    private BillCompareConfig billCompareConfig;

    /**
     * 对账任务步骤编排
     * @return
     */
    @Bean
    public Job wexinBillCompareJob() {
        return jobBuilderFactory.get("wexinBillCompareJob")
                .incrementer(new RunIdIncrementer())
                .listener(wexinDetailReadListener)
                .start(wexinPaymentLogStep())
                .next(wexinRefundLogStep())
                .build();
    }

    /**
     * 微信还款对账任务步骤定义-交易明细
     * @return
     */
    @Bean
    public Step wexinPaymentLogStep() {
        return stepBuilderFactory.get("wexinPaymentLogStep")
                .<TlPaymentLog, ThirdBillDetilReadBean>chunk(anytxnBatchConfigProperties.getBatchBillCompareConfiguration().getChunkLimit())
                .reader(wexinPaymentLogReader(null, null))
                .processor(wexinPaymentLogProcessor)
                .writer(billDetailWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchConfigProperties.getBatchBillCompareConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    /**
     * 微信还款对账任务定义-三方明细
     * @return
     */
    @Bean
    public Step wexinRefundLogStep() {
        return stepBuilderFactory.get("wexinRefundLogStep")
                .<TlRefundLog, ThirdBillDetilReadBean>chunk(anytxnBatchConfigProperties.getBatchBillCompareConfiguration().getChunkLimit())
                .reader(wexinRefundLogReader(null, null))
                .processor(wexinRefundLogProcessor)
                .writer(billDetailWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchConfigProperties.getBatchBillCompareConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    /**
     * 微信还款对账步骤reader
     */
    @Bean
    @StepScope
    public MyBatisPagingItemReader<TlPaymentLog> wexinPaymentLogReader(@Value("#{jobExecutionContext['PR_ORG_TODAY']}") Date today,
                                                                       @Value("#{jobExecutionContext['PR_ORG_TENANT']}") String tenantId) {
        final String queryId = "com.jrx.anytxn.transaction.mapper.ext.ExtTlPaymentLogMapper.selectForBillComparing";
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(4);
        param.put("tenantId", tenantId);
        param.put("businessDate", today);
        param.put("thirdChannel", billCompareConfig.getThirdChannel());
        return initReader(bizSqlSessionFactory, queryId, param, anytxnBatchConfigProperties.getBatchBillCompareConfiguration().getPageSize());
    }

    /**
     * 微信还款-退货对账步骤reader
     */
    @Bean
    @StepScope
    public MyBatisPagingItemReader<TlRefundLog> wexinRefundLogReader(@Value("#{jobExecutionContext['PR_ORG_TODAY']}") Date today,
                                                                     @Value("#{jobExecutionContext['PR_ORG_TENANT']}") String tenantId) {
        final String queryId = "com.jrx.anytxn.transaction.mapper.ext.ExtTlRefundLogMapper.selectForBillComparing";
        Map<String, Object> param = Maps.newHashMapWithExpectedSize(4);
        param.put("tenantId", tenantId);
        param.put("businessDate", today);
        param.put("thirdChannel", billCompareConfig.getThirdChannel());
        return initReader(bizSqlSessionFactory, queryId, param, anytxnBatchConfigProperties.getBatchBillCompareConfiguration().getPageSize());
    }

    private <T> MyBatisPagingItemReader<T> initReader(SqlSessionFactory factory, String queryId, Map<String, Object> params, Integer pageSize) {
        MyBatisPagingItemReader<T> reader = new MyBatisPagingItemReader<>();
        reader.setSaveState(false);
        reader.setSqlSessionFactory(factory);
        reader.setPageSize(pageSize);
        reader.setQueryId(queryId);
        reader.setParameterValues(params);
        return reader;
    }

}
